package com.yiyuzi.wiki.spine;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yiyuzi.wiki.common.LogRecord;
import com.yiyuzi.wiki.common.ResponseDTO;
import com.yiyuzi.wiki.common.utils.ConvertUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author hongxy
 * @date 2021/7/2 9:37
 */

@RestController
@RequestMapping("/spine")
public class SpineController {
    private static final Logger LOGGER = LoggerFactory.getLogger(SpineController.class);

    @Resource
    private SpineService spineService;

    @LogRecord
    @RequestMapping("/hello")
    public String hello() {
        return "welcome!";
    }

    @LogRecord
    @RequestMapping("/set")
    public ResponseDTO<Boolean> setSpine() {
        return ResponseDTO.res(spineService.setSpine());
    }

    @LogRecord
    @RequestMapping("/setText")
    public ResponseDTO<Boolean> setSpineText() {
        return ResponseDTO.res(spineService.setSpineText());
    }

    @LogRecord
    @RequestMapping("/setPng")
    public ResponseDTO<Boolean> setSpinePng() {
        return ResponseDTO.res(spineService.setSpinePng());
    }

    @LogRecord
    @RequestMapping("/list")
    public ResponseDTO getSpinePage(HttpServletRequest request, HttpServletResponse response) {
        String chineseName = request.getParameter("chineseName");
        String name = request.getParameter("name");
        long size = Long.parseLong(request.getParameter("size"));
        long current = Long.parseLong(request.getParameter("current"));
        Page<SpineEntity> page = new Page<>(current, size);
        page.addOrder(OrderItem.asc("chinese_name"));
        // 过滤所有无中文的spine（因为这些暂时不能显示）
        IPage<SpineEntity> iPage = spineService.page(page, new QueryWrapper<SpineEntity>()
                .eq("father_id", 0)
                .isNotNull("chinese_name")
                .like(chineseName != null && !chineseName.equals(""), "chinese_name", chineseName)
                .like(name != null && !name.equals(""), "name", name));
        return ResponseDTO.res(ConvertUtils.convertPageResult(iPage));
    }

    // 开发接口
    @RequestMapping("/createlistNullCName")
    public ResponseDTO getSpinePageByNullCName(HttpServletRequest request, HttpServletResponse response) {
        long size = Long.parseLong(request.getParameter("size"));
        long current = Long.parseLong(request.getParameter("current"));
        Page<SpineEntity> page = new Page<>(current, size);
        page.addOrder(OrderItem.asc("name"));
        IPage<SpineEntity> iPage = spineService.page(page, new QueryWrapper<SpineEntity>()
                .eq("father_id", 0)
                .isNull( "chinese_name"));
        return ResponseDTO.res(ConvertUtils.convertPageResult(iPage));
    }

    // 开发接口
    @RequestMapping("/createlist")
    public ResponseDTO getSpinePageByName(HttpServletRequest request, HttpServletResponse response) {
        String chineseName = request.getParameter("chineseName");
        long size = Long.parseLong(request.getParameter("size"));
        long current = Long.parseLong(request.getParameter("current"));
        Page<SpineEntity> page = new Page<>(current, size);
        page.addOrder(OrderItem.asc("name"));
        IPage<SpineEntity> iPage = spineService.page(page, new QueryWrapper<SpineEntity>()
                .eq("father_id", 0)
                .like(chineseName != null && !chineseName.equals(""), "chinese_name", chineseName));
        return ResponseDTO.res(ConvertUtils.convertPageResult(iPage));
    }

    @RequestMapping("/update")
    public ResponseDTO<String> updateSpine(HttpServletRequest request, HttpServletResponse response) {
        String chineseName = request.getParameter("chineseName");
        long id = Long.parseLong(request.getParameter("id"));
        return ResponseDTO.res(spineService.update(new UpdateWrapper<SpineEntity>()
                .eq("id", id)
                .set(chineseName != null && !chineseName.equals(""), "chinese_name", chineseName)));
    }

    @RequestMapping("/get")
    public void getSpine(HttpServletRequest request, HttpServletResponse response) {
        try {
            long father_id = Long.parseLong(request.getParameter("fatherId"));
            String type = request.getParameter("type");
            SpineEntity spineEntity = spineService.getOne(new QueryWrapper<SpineEntity>()
                    .eq("father_id", father_id)
                    .eq("type", type));
            if (spineEntity == null) {
                response.sendError(404);
                return;
            }
            String url = spineEntity.getPath();
//            LOGGER.info(url);
            File file = new File(url);
            //判断文件是否存在
            if (!(file.exists() && file.canRead())) {
                response.sendError(404);
                return;
            }
            FileInputStream inputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            int length = inputStream.read(data);
            inputStream.close();
//            response.setContentType("text/plain;charset=utf-8");
            OutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();
            stream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        return response;
    }

    // 获取图片文件，例：http://49.234.88.43:8080/wiki/spine/hongzhi.png
    @RequestMapping("/{name}")
    public void getSpinePng(@PathVariable("name") String name, HttpServletRequest request, HttpServletResponse response) {
        try {
            SpineEntity spineEntity = spineService.getOne(new QueryWrapper<SpineEntity>()
                    .eq("name", name)
                    .eq("type", "png"));
            if (spineEntity == null) {
                response.sendError(404);
                return;
            }
            String url = spineEntity.getPath();
//            LOGGER.info(url);
            File file = new File(url);
            //判断文件是否存在
            if (!(file.exists() && file.canRead())) {
                response.sendError(404);
                return;
            }
            InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
            byte[] data = new byte[inputStream.available()];
            int length = inputStream.read(data);
            inputStream.close();
            response.reset();
            response.addHeader("Content-Length", "" + data.length);
//            response.setContentType("application/x-download");//设置response内容的类型 普通下载类型
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));//设置头部信息
            response.setHeader("Access-Control-Allow-Origin", "*");
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(data);
            outputStream.flush();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
